package model.action;

import datacontainer.ImmuTable;
import java.util.List;


/**
 * Class converts every (convertible) in the table to a percentage
 * of the column total. It will first find the sum of each column
 * (each column that is summable). And then it will replace each
 * element with its corresponding percentage. If the element is not
 * of the number format, the element will be replaced with a "".
 * Note: the result will not have a summation row as the bottom row.
 * 
 * @author Michael Deng
 * 
 */
public class PercentifyTable extends TableAction {

    private static final double ONE_HUNDRED = 100;

    @Override
    public void setInput (String column, List<String> conditions) {
        super.setInput(column, conditions);
    }

    @Override
    public void execute (ImmuTable workSpace, ImmuTable rawData) {
        // must execute a SumColumnTable first
        sumColumnTableAction(workSpace);

        for (int i = 0; i < workSpace.getHeaders().size(); i++) {
            if (checkPercentifiableType(workSpace, i)) {
                convertColumnToPercent(workSpace, i);
            }
        }
        // deletes the final "sum" row created by the superclass constructor
        removeRow(workSpace, workSpace.getData().get(0).size() - 1);
    }

    /**
     * 
     * @param columnIndex index of the column
     * @return
     */
    private boolean checkPercentifiableType (ImmuTable workSpace, int columnIndex) {
        List<String> type = workSpace.getTypes();
        return "Double".equals(type.get(columnIndex));
    }

    /**
     * Converts each element in the specified column to a
     * percentage of the total. The resulting column is still
     * in an List<String> format.
     * 
     * @param columnIndex
     */
    private void convertColumnToPercent (ImmuTable workSpace, int columnIndex) {
        List<String> column = workSpace.getData().get(columnIndex);
        String value = column.get(column.size() - 1);
        double columnSum = -1;
        if (!"".equals(value)) {
            columnSum = Double.parseDouble(value);
        }
        for (int i = 0; i < column.size(); i++) {
            String e = column.get(i);
            if (!"".equals(e)) {
                double result = Double.parseDouble(e) * ONE_HUNDRED / columnSum;
                if (columnSum == -1) {
                    result = 0;
                }
                e = Double.toString(result);
            }
            else {
                e = "0";
            }
            column.set(i, e);
        }
    }
}
